<template>
  <div class="user">
    <van-nav-bar
      class="user-bar"
      title="个人信息"
      left-arrow
      @click-left="back"
    />
    <div class="user-body">
      <input
        type="file"
        hidden
        id="file"
        accept="image/*"
        ref="file"
        @change="change"
      />
      <van-cell title="头像">
        <label for="file">
          <van-image round width="3rem" height="3rem" :src="userInfo.avatar" />
        </label>
      </van-cell>
      <van-cell
        title="昵称"
        :to="{ path: '/edit', query: { nickname: userInfo.nickname } }"
        is-link
        :value="userInfo.nickname"
      />
      <van-cell
        title="性别"
        @click="sexPickerShow = true"
        is-link
        :value="userInfo.sex || '请选择性别'"
      />

      <van-popup v-model="sexPickerShow" position="bottom">
        <van-picker
          @confirm="sexPickConfirm"
          @cancel="sexPickerShow = false"
          title="请选择"
          :columns="sexColumns"
          show-toolbar
        />
      </van-popup>

      <van-cell
        title="生日"
        is-link
        @click="datePickerShow = true"
        :value="userInfo.birthday || '请选择生日'"
      />
      <van-popup v-model="datePickerShow" position="bottom">
        <van-datetime-picker
          :value="
            userInfo.birthday
              ? new Date(userInfo.birthday)
              : new Date(2000, 0, 1)
          "
          type="date"
          title="选择年月日"
          :min-date="minDate"
          :max-date="maxDate"
          @confirm="datePickConfirm"
          @cancel="datePickerShow = false"
        />
      </van-popup>
    </div>
    <div class="user-btn">
      <van-button @click="getData()" type="primary" block>确定</van-button>
    </div>
  </div>
</template>

<script>
import sexPickerMixin from "./sexPickerMixin";
import datePickerMixin from "./datePickerMixin";
import { getuserInfo, getToken } from "@/api/api";
import { Toast } from "vant";
export default {
  data() {
    return {
      
      nickname:'',
      
      
      uid_1: "",
      token_1: "",
      userInfo: {},
    };
  },
  created() {
    this.uid_1 = localStorage.getItem("uid");
    this.token_1 = localStorage.getItem("token");

    
  },

  mixins: [sexPickerMixin, datePickerMixin],
  mounted() {
    this.getuserInfo();

    // let nickname = sessionStorage.getItem('nickname')
    // if(nickname){
    //   this.nickname = nickname
    // }
  },
  activated(){
     let nickname = sessionStorage.getItem('nickname')
    if(nickname){
      this.userInfo.nickname = nickname
     }
 },
 //  被缓存的组件 加入到缓存时  
 deactivated(){
    console.log('加入到缓存')
 },
  
  
  methods: {
    back() {
      this.$router.push("/my");
    },
    //获取用户信息
    getuserInfo() {
      let { token_1 } = this;
      getuserInfo({ token: token_1 }).then((res) => {
        console.log(res);
        this.userInfo = res.data.userInfo;
        console.log(this.userInfo);
      });
    },
    ///  上传
    async upload(fileList) {
      let imageSrc = [];
      if (!fileList || !Array.isArray(fileList) || fileList.length === 0) {
        //  没上传图片
        return imageSrc;
      }

      // 需要 循环
      //  多个异步任务都执行完成  返回他们完成后的结果
      let task = fileList.map((v) => {
        return new Promise(async (resolve, reject) => {
          let { file } = v;
          let { type } = file;
          //  拿到类型  比如jpg image/jpg
          type = type.split("/")[1];
          // 重新命名  随机名字
          let file_name = `${new Date().getTime()}_${Math.random()
            .toString(36)
            .slice(2)}.${type}`;
          // 去服务器申请一个上传token

          let k = await getToken();

          console.log(k.data.token);

          const formdata = new FormData();
          formdata.append("file", file);
          formdata.append("token", k.data.token);
          formdata.append("key", file_name);

          this.$http
            .post("https://upload-z1.qiniup.com", formdata)
            .then((res) => {
              console.log(res);
              resolve(`http://toutiao.longxiaokj.com/` + res.data.key);
            });
        });
      });
      

      // task  [promises,promise]

      imageSrc = await Promise.all(task);

      return imageSrc;
     
    },

    

    async change(e) {
      console.log(); //  没有使用vant   我们把他封装成vant的

      let file = e.target.files[0]; //  二进制

      //  1  前端预览 FileReader   base64
      //  2 URL.createObjectURL  前端预览图片  1
      this.userInfo.file = file;
      let fileReader = new FileReader();
      fileReader.readAsDataURL(file);
      fileReader.onload = (e) => {
        this.userInfo.avatar = e.target.result;
      };
    },

    async getData() {
      if (file) {
        //证明上传头像
        let {
         
          file,
        } = this.userInfo;
        let fileList = [
          {
            file,
          },
        ]; //和vant上传组件形状一样

        let res = await this.upload(fileList);

        this.avatar = res[0];
      }

      //修改用户信息
      this.$http
        .post("/user/editUserInfo", {
          nickname:this.userInfo.nickname,
          avatar:this.avatar,
          sex:this.userInfo.sex,
          birthday:this.userInfo.birthday,
          uid: this.uid_1,
        })
        .then((res) => {
          console.log(res);
          this.$toast(res.data.msg);
          // this.userInfo=res.data.userInfo
          if (res.data.code == 0) {
            setTimeout((v) => {
              this.$router.back();
            }, 500);
          }
        });
    },
  },
};
</script>

<style>
.user {
  position: relative;
}

.user-btn {
  position: absolute;
  left: 13px;
}
.user-btn button {
  width: 350px;
}
.user-bar {
  background: #07c060;
}
.van-nav-bar__title {
  color: white;
}
</style>